#include "appXssl.h"

extern xsUserCfg_t s_stUserCfg;

int uart1_get_user_cmd(unsigned char *pucCmdCode, unsigned char *pucValue, unsigned char ucSize)
{
	int iRet = UART1_NO_CMD;
	int iCh = 0;
	unsigned char ucCh = 0;
	static unsigned char  ucStep = 0;
	static unsigned char  ucPos = 0;
  
  iCh = uart1_recv_char();
	if(0 < iCh){
		ucCh = (unsigned char)iCh;
		console_log("%X ", ucCh);
		switch(ucStep){
			case 0:
				if(UART_USER_CMD_TAG == ucCh){
					ucStep = 1;
				}
				break;
			case 1:
				*pucCmdCode = ucCh;
				switch(*pucCmdCode){
          case SET_SN_CMD:
          case SET_PW_CMD:
            ucStep = 2;
            break;
					default:
						ucStep = 0;
						iRet = UART1_INVALID_CMD;
						break;
				}
				break;
			case 2:
				if(UART_USER_CMD_END == ucCh){
					ucStep = 0;
          ucPos = 0;
          iRet = UART1_OK;
					break;
				}
				if(ucSize == ucPos){
          ucStep = 0;
          ucPos = 0;
					break;
				}
				pucValue[ucPos++] = ucCh;
				break;				
			default :
				ucStep = 0;
				iRet = UART1_ERR;
				break;
		}
	}else{
		iRet = UART1_R_ERR;
	}
	return iRet;
}

int get_user_cfg(void)
{
  int iRet ;
  unsigned char ucCmd,
                aucValue[XS_DEV_SN_LEN] = {0};
  read_again:
  iRet = user_cfg_read();
  if(0 > iRet){
    print_log(D_ERROR, ("Plesse initialize device information\n")); 
    set_gprs_timing_delay(500);
    while(1){
      if(0 == get_func_timing_delay()){
        buzzer_ring(1);
        set_func_timing_delay(500);
      }
      iRet = uart1_get_user_cmd(&ucCmd, aucValue, XS_DEV_SN_LEN);
      if(S_OK == iRet){
        if(SET_SN_CMD == ucCmd){
          //print_hex("G-SN:", aucValue, XS_DEV_SN_LEN);
          memcpy(s_stUserCfg.acSn, aucValue, XS_DEV_SN_LEN);
        }

        if(SET_PW_CMD == ucCmd){
          //print_hex("G-PW:", aucValue, XS_DEV_SN_LEN);
          memcpy(s_stUserCfg.acPwd, aucValue, XS_DEV_SN_LEN);
          user_cfg_write(WRITE_DEV_INFO);
        }
        memset(aucValue, 0, XS_DEV_SN_LEN);
        if(SET_PW_CMD == ucCmd){
          goto read_again;
        }
      }
    }
  }else if(1 == iRet){
    user_cfg_write(WRITE_CFG_INFO);
  }
  return 0;
}


